package model

import (
	"encoding/json"
	"time"
	"cmsapi/src/lib"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type LogModel struct {
	//http://127.0.0.1:9900/v1/home/activity/detail?token=1111&username=abc&page=2
	ID       int64  `json:"id"  form:"id"` //`资讯 ID`
	Type     string `json:"type" form:"type"`
	Method   string `json:"method" form:"method"`
	Url      string `json:"url" form:"url"`
	Content  string `json:"content" form:"content"`
	Ip       string `json:"ip" form:"ip"`
	Token    string `json:"token" form:"token"`
	UserId   int64  `json:"user_id" form:"user_id"`
	UserName string `json:"user_name" form:"user_name"`
	AddTime  int64  `json:"add_time" form:"add_time"`

	//Title string `json:"title" form:"title" binding:"min=4,max=20,required"` //`资讯 标题`

	//reqdred=ID 不是和id内容是一样的。
	//omitempty 为空 或者大于0
	//dive 继承上一级的验证
	//	UserId int
	//UserName string
}

func LogCreate(c *gin.Context, db *gorm.DB, log map[string]interface{}) bool {

	//db := lib.Mysql
	//c.RemoteIP()
	//	fmt.Println("RequestURL", c.GetHeader("Request_URL"), "-", c.GetHeader("url"), c.Request.RequestURI)

	//鉴权

	var logData LogModel
	logData.Type = (log["type"]).(string)
	logData.Method = (log["method"]).(string)
	if logData.Type == "post" {
		logContent := make(map[string]interface{}) //注意该结构接受的内容
		c.BindJSON(&logContent)
		content, _ := json.Marshal(logContent) //"content": string(content),
		logData.Content = string(content)
	}
	logData.Token = (log["token"]).(string)

	//	s := *http.Request
	logData.Url = c.Request.RequestURI
	logData.Ip = c.ClientIP()
	logData.AddTime = time.Now().Unix()

	var userInfo UserModel

	//取用户信息
	redisKey := "login:user:token:" + logData.Token

	d1, _ := lib.RedisGet(redisKey)
	json.Unmarshal([]byte(d1), &userInfo)
	//logData.UserId = strconv.FormatInt(strconv.FormatFloat(((userInfo["id"]).(float64)), 'E', -1, 64), 10)
	//logData.UserName = ((userInfo["user_name"]).(string))
	//用户信息结束
	//strings := strconv.FormatFloat((userInfo["id"]).(float64), 'E', -1, 64)
	logData.UserId = userInfo.ID
	logData.UserName = userInfo.UserName
	//fmt.Printf("logData %s %T /r/n", userInfo, userInfo.UserName)
	//写入日志
	//	log["type"]

	result2 := db.Debug().Table(lib.DbInfo.Prefix + "log").Create(&logData)
	if result2.Error != nil { // 遇到错误时回滚事务
		//	c.Set("code", 929)
		//	tx.Rollback()
		//	c.Next()
		return false
	} else {
		return true
	}

	//	return true
}

/*
//gorm 查询
func ActivityGormDetail(data ActivityData) ActivityData  {
	dsn := "root:root@tcp(127.0.0.1:3306)/txgo?charset=utf8mb4&parseTime=True&loc=Local"
	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	db.Raw("SELECT * FROM users WHERE id = ?", 1).Scan(&ActivityData)
	return ActivityData

}
*/
